package com.longkier.gx_library_springboot.Service;

import com.longkier.gx_library_springboot.entity.Notice;
import com.longkier.gx_library_springboot.repository.NoticeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class NoticeService {
    private final NoticeRepository noticeRepository;

    public List<Notice> getAllNotices() {
        return noticeRepository.findAll();
    }

    public Notice getNoticeById(Long noticeId) {
        return noticeRepository.findById(noticeId)
                .orElseThrow(() -> new RuntimeException("公告不存在"));
    }

    public Notice createNotice(Notice notice) {
        notice.setCreateTime(LocalDateTime.now());
        notice.setUpdateTime(LocalDateTime.now());
        return noticeRepository.save(notice);
    }

    public Notice updateNotice(Long noticeId, Notice notice) {
        Notice existingNotice = getNoticeById(noticeId);
        existingNotice.setNoticeTitle(notice.getNoticeTitle());
        existingNotice.setNoticeContent(notice.getNoticeContent());
        existingNotice.setUpdateTime(LocalDateTime.now());
        return noticeRepository.save(existingNotice);
    }

    public void deleteNotice(Long noticeId) {
        noticeRepository.deleteById(noticeId);
    }
}
